//
//  SEGVisitorAccessViewController.m
//  ExcellentHome
//
//  Created by 乔杨 on 2020/6/3.
//
//生成访客通行证界面／访客历史详情界面

#import "SEGVisitorAccessViewController.h"
#import "SEGVisitorAccessDoorViewController.h"
#import "SEGVisitorAccessHistoryViewController.h"
#import "SEGVisitorAccessCodeViewController.h"
#import "SEGVisitorAccessNumberViewController.h"
#import "SEGVisitorAccessHouseViewController.h"

#import "SEGVisitorAccessTableViewCell.h"

#import "SEGVisitorAccessViewModel.h"

@interface SEGVisitorAccessViewController ()<UITableViewDelegate, UITableViewDataSource, SEGVisitorAccessSelectHouseDelegate, SEGVisitorAccessSelectDoorDelegate, SEGVisitorAccessSelectNumberDelegate, UITextFieldDelegate>

/// 信息列表视图
@property (nonatomic, strong)UITableView *tableView;
/// 生成通行证按钮
@property (nonatomic, strong)UIButton *createButton;
/// 访客姓名填写控件
@property (nonatomic, strong)UITextField *nameField;
/// 访客电话填写控件
@property (nonatomic, strong)UITextField *phoneField;
/// 车牌号
@property (nonatomic, strong)UITextField *carNoField;
/// 房间号
@property (nonatomic, strong)UITextField *houseField;
/// 可用次数
@property (nonatomic, strong)UITextField *numberFeild;
/// 授权门禁
@property (nonatomic, strong)UITextField *doorFeild;
/// 房屋列表
@property (nonatomic, strong) SEGVisitorAccessHouseViewController *houseViewController;
/// 选择次数视图
@property (nonatomic, strong)SEGVisitorAccessNumberViewController *numberViewController;
/// 门禁列表
@property (nonatomic, strong)SEGVisitorAccessDoorViewController *doorViewController;

/// viewModel
@property (nonatomic, strong) SEGVisitorAccessViewModel *viewModel;

@end

@implementation SEGVisitorAccessViewController
 
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kColor_bg;
    if (self.model) {
        self.title = self.title.length > 0?self.title :@"访客历史详情";
    } else {
        self.title = self.title.length > 0?self.title : @"访客通行";
        [self showCustomNavigationRightButtonWithTitle:@"访客历史" image:nil hightlightImage:nil color:kColor_T];
    }
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    [self seg_RACBind];
}
- (void)seg_RACBind {
    if (self.model) { // 分享通行证
        @weakify(self);
        [[self.createButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self);
            [self.viewModel seg_sharePass];
            [[self.viewModel.shareCommand execute:self.model.vistLogid] subscribeNext:^(id  _Nullable x) {
                SEGVisitorAccessCodeViewController *codeVC = [[SEGVisitorAccessCodeViewController alloc] init];
                [self.navigationController pushViewController:codeVC animated:YES];
            } error:^(NSError * _Nullable error) {
                if (error.code == 1) {
                    [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason withtime:1.0];
                } else {
                    [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
                }
            }];
        }];
    } else { // 生成通行证
        @weakify(self);
        [[self.createButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self);
            [self.viewModel seg_createPass];
            [self.viewModel.passSignal subscribeNext:^(id  _Nullable x) {
                SEGVisitorAccessCodeViewController *codeVC = [[SEGVisitorAccessCodeViewController alloc] init];
                [self.navigationController pushViewController:codeVC animated:YES];
                
            } error:^(NSError * _Nullable error) {
                [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
            }];
        }];
    }
}

#pragma mark - Event
// 访客历史
- (void)onNavigationRightButtonClicked:(UIButton*)sender {
    SEGVisitorAccessHistoryViewController *historyVC = [[SEGVisitorAccessHistoryViewController alloc] init];
    [self.navigationController pushViewController:historyVC animated:YES];
}

#pragma mark - SEGVisitorAccessSelectHouseDelegate(选择房屋返回代理方法)
- (void)selectedHouseName:(NSString *)houseName houseId:(NSString *)houseId {
    self.viewModel.houseName = houseName;
    self.viewModel.houseId = houseId;
}
#pragma mark - SEGVisitorAccessSelectNumberDelegate(选择门禁返回代理方法)
- (void)selectedNumber:(NSString *)number {
    self.viewModel.selectedNumber = number;
}
#pragma mark - SEGVisitorAccessSelectDoorDelegate(选择门禁返回代理方法)
- (void)selectedDoorsWithDict:(NSDictionary *)doorInfoDict {
    self.viewModel.doorInfoDict = doorInfoDict;
}

#pragma mark - UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) return 4;
    return 2;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SEGVisitorAccessTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kVisitorAccessTableViewCellIdentifier forIndexPath:indexPath];
    switch (indexPath.section) {
        case 0:
        {
            switch (indexPath.row) {
                case 0:
                {
                    cell.lable.text = @"访客姓名";
                    cell.textField.placeholder = kCustomerNamePlaceholder;
                    self.nameField = cell.textField;
                    RACChannelTo(self.viewModel, custNameStr) = self.nameField.rac_newTextChannel;
                    cell.selectImage.hidden = YES;
                    break;
                }
                case 1:
                {
                    cell.lable.text = @"访客电话";
                    cell.textField.placeholder = kCustomerPhonePlaceholder;
                    self.phoneField = cell.textField;
                    self.phoneField.keyboardType = UIKeyboardTypeNumberPad;
                    // 双向绑定
                    RACChannelTo(self.viewModel, phoneStr) = self.phoneField.rac_newTextChannel;
                    // 限制手机号长度
                    @weakify(self);
                    [[self.phoneField.rac_textSignal filter:^BOOL(NSString * _Nullable value) {
                        return value.length >= kPhoneMaxLength;
                    }] subscribeNext:^(NSString * _Nullable x) {
                        @strongify(self);
                        self.viewModel.phoneStr = [self.phoneField.text substringToIndex:kPhoneMaxLength];
                    }];
                    cell.selectImage.hidden = YES;
                    break;
                }
                case 2:
                {
                    cell.lable.text = @"车牌号";
                    cell.textField.placeholder = @"请输入车牌号(非必填)";
                    self.carNoField = cell.textField;
                    RACChannelTo(self.viewModel, carNumberStr) = self.carNoField.rac_newTextChannel;
                    cell.selectImage.hidden = YES;
                    break;
                }
                case 3:
                {
                    cell.lable.text = @"我的房间号";
                    self.houseField = cell.textField;
                    RAC(self.houseField, text) = [RACObserve(self.viewModel, houseName) takeUntil:cell.rac_prepareForReuseSignal];
                    self.houseField.userInteractionEnabled = NO;
                    cell.selectImage.hidden = NO;
                    break;
                }
                default:
                    break;
            }
            break;
        }
        case 1:
        {
            switch (indexPath.row) {
                case 0:
                {
                    cell.lable.text = @"可用次数";
                    self.numberFeild = cell.textField;
                    @weakify(self);
                    [[RACObserve(self.viewModel, selectedNumber) takeUntil:cell.rac_prepareForReuseSignal] subscribeNext:^(id  _Nullable x) {
                        @strongify(self);
                        self.numberFeild.text = [NSString stringWithFormat:@"%@ 次",self.viewModel.selectedNumber];
                    }];
                    break;
                }
                case 1:
                {
                    cell.lable.text = @"授权门禁";
                    cell.textField.placeholder = @"请选择授权门禁(非必填)";
                    self.doorFeild = cell.textField;
                    @weakify(self);
                    [[RACObserve(self.viewModel, doorInfoDict) takeUntil:cell.rac_prepareForReuseSignal] subscribeNext:^(id  _Nullable x) {
                        @strongify(self);
                        self.doorFeild.text = self.viewModel.doorInfoDict[@"doorNames"];
                    }];
                    break;
                }
                default:
                    break;
            }
            cell.textField.userInteractionEnabled = NO;
            cell.selectImage.hidden = NO;
            break;
        }
        default:
            break;
    }
    if (self.model) {
        self.carNoField.placeholder =  @"未填写";
        self.doorFeild.placeholder =  @"未填写";
        cell.textField.userInteractionEnabled = NO;
        cell.selectImage.hidden = YES;
        // 数据绑定
        [self.viewModel seg_bindDataWithModel:self.model];
    }
    return cell;
}
#pragma mark - UITableViewDelegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44.0;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 0) return 10.0;
    return 20.0;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, LYScreenWidth(), 20)];
    footView.backgroundColor = kColor_bg;
    return footView;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (self.model) return;
    
    if (indexPath.section == 0) {
        [self.view endEditing:YES];
        if (indexPath.row == 3) { // 选择房屋
            self.houseViewController.houseId = self.viewModel.houseId;
            [self.navigationController pushViewController:self.houseViewController animated:YES];
        }
    } else if (indexPath.section == 1) {
        [self.view endEditing:YES];
        if (indexPath.row == 0) {//可用次数
            //显示选择次数视图
            [self.navigationController pushViewController:self.numberViewController animated:YES];
        }else {//授权门禁
            //显示门禁列表界面
            [self.navigationController pushViewController:self.doorViewController animated:YES];
        }
    }
}
// 设置分割线
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    UIEdgeInsets insets = UIEdgeInsetsZero;//屏幕等宽分割线
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:insets];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:insets];
    }
    if ([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {
        [cell setPreservesSuperviewLayoutMargins:NO];
    }
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:insets];
    }
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:insets];
    }
}

#pragma mark - Getter
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kNavigationBarAndStatusBarHeight, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame)-kNavigationBarAndStatusBarHeight) style:UITableViewStylePlain];
        _tableView.backgroundColor = kColor_bg;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorColor = kColor_L2;
        [_tableView registerClass:[SEGVisitorAccessTableViewCell class] forCellReuseIdentifier:kVisitorAccessTableViewCellIdentifier];
        UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, LYScreenWidth(), 44)];
        [footView addSubview:self.createButton];
        _tableView.tableFooterView = footView;
    }
    return _tableView;
}
- (UIButton *)createButton {
    if (!_createButton) {
        CGRect rect = CGRectMake(15, 0, LYScreenWidth() - 30.0, 44);
        _createButton = [[UIButton alloc] initWithFrame:rect];
        [_createButton setBackgroundImage:[UIImage imageWithColor:kColor_T] forState:UIControlStateNormal];
        [_createButton setBackgroundImage:[UIImage imageWithColor:kColor_T_Press] forState:UIControlStateHighlighted];
        [_createButton setTitleColor:kColor_W forState:UIControlStateNormal];
        _createButton.titleLabel.font = kFont_16;
        _createButton.layer.masksToBounds = YES;
        _createButton.layer.cornerRadius = 2.0;
        if (self.model) {
            [_createButton setTitle:@"分享通行证" forState:UIControlStateNormal];
        } else {
            [_createButton setTitle:@"生成通行证" forState:UIControlStateNormal];
        }
    }
    return _createButton;
}
- (SEGVisitorAccessViewModel *)viewModel {
    if (!_viewModel) _viewModel = [[SEGVisitorAccessViewModel alloc] init];
    return _viewModel;
}
- (SEGVisitorAccessHouseViewController *)houseViewController {
    if (!_houseViewController) {
        _houseViewController = [[SEGVisitorAccessHouseViewController alloc] init];
        _houseViewController.delegate = self;
    }
    return _houseViewController;
}
- (SEGVisitorAccessNumberViewController *)numberViewController {
    if (!_numberViewController) {
        _numberViewController = [[SEGVisitorAccessNumberViewController alloc] init];
        _numberViewController.delegate = self;
    }
    return _numberViewController;
}
- (SEGVisitorAccessDoorViewController *)doorViewController {
    if (!_doorViewController) {
        _doorViewController = [[SEGVisitorAccessDoorViewController alloc] init];
        _doorViewController.delegate = self;
    }
    return _doorViewController;
}

@end
